package com.qf.filter;

import cn.hutool.json.JSONUtil;
import com.qf.config.RedisKeyConfig;
import com.qf.config.SystemConfig;

import com.qf.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Filter;
import java.util.logging.LogRecord;

@Component
@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        String url=request.getRequestURI();
        log.info("请求路径-{}",url);
        //验证是否为接口
        if(url.contains("api/")){
            //是否需要验证 令牌 不需要验证：注册、登录、密码找回
            if(!url.contains("user/")){
                //需要登录 才可访问
                String token=request.getHeader(SystemConfig.HEADER_TOKEN);
                if(!stringRedisTemplate.hasKey(RedisKeyConfig.USER_TOKEN+token)){
                   //令牌 无效 拦截
                    HttpServletResponse response=(HttpServletResponse) servletResponse;
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().println(JSONUtil.toJsonStr(R.fail("亲，请登录之后再来访问！")));
                    return;
                }else {
                    //令牌有效 续期
                    stringRedisTemplate.expire(RedisKeyConfig.USER_TOKEN+token,2, TimeUnit.HOURS);
                }
            }
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public boolean isLoggable(LogRecord record) {
        return false;
    }
}
